package com.wontube.smr.web.pub;

import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.wontube.client.extension.utils.StringUtils;
import com.wontube.smr.web.utils.SmrCookieUtils;

/**
 * @author tanggf(2012-5-16)
 *
 */
public class SmrInterceptor extends HandlerInterceptorAdapter{
	private final static Logger logger = LoggerFactory.getLogger(SmrInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Cookie[] cookies = request.getCookies();
		String sessionId = "";
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (RequestHeadersHolder.sessionKey.equalsIgnoreCase(cookie.getName())) {
					sessionId = cookie.getValue();
					break;
				}
			}
		}		
		
		String serverSessionId = sessionId;
		if ("".equals(sessionId)) {
			// suppose that session id starts with __$__ is trusted by server
			// and will be cleared
			sessionId = UUID.randomUUID().toString();
			serverSessionId = "__$__" + sessionId;
			
			// 更新cookie
			Cookie cookie = new Cookie(RequestHeadersHolder.sessionKey, sessionId);
			cookie.setPath("/");
			cookie.setMaxAge(-1); // 关闭浏览器即清除
			response.addCookie(cookie);
		}		
		
		String remoteIp = request.getHeader("X-Real-IP");
		if (StringUtils.isNullOrEmpty(remoteIp) || "unknown".equalsIgnoreCase(remoteIp)) {
			remoteIp = request.getRemoteAddr();
		}
		
		HashMap<String, String> header = RequestHeadersHolder.holder.getHeader();
		
		header.put(RequestHeadersHolder.sessionKey, serverSessionId);
		header.put(RequestHeadersHolder.ipKey, remoteIp);
		RequestHeadersHolder.holder.setHeaders(header);
		
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if(modelAndView != null) {
			modelAndView.addObject("contextPath", request.getContextPath());
			modelAndView.addObject("servletPath", request.getServletPath());				
			//来源
			String ref = SmrCookieUtils.getRefCookie(request);
			if(ref == null){
				ref = "";
			}
			modelAndView.addObject("ref", ref);
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		RequestHeadersHolder.holder.remove();
		if(ex != null){
			String msg = "error happen when SpringMVC handling [{}] request: ";
			String path = request.getPathInfo();
			if(path == null){
				path = request.getServletPath();
			}
			logger.error(msg, path, ex);
		}
	}
}
